var express = require('express');
var router = express.Router();
var dataLoader = require('./../kylin/dataLoader');
const {User, PortalJobMeta, sequelize} = require('../kylin/database');
const request = require('sync-request');

router.get('/columns/:table', function (req, res, next) {
    console.log(req.params);
    var columns = dataLoader.getColumns(req.params.table);
    res.json(columns);
});

router.use('/query', function(req, res, next) {
    // console.log(req.body);
    var task_id = req.query.task_id;
    var table = req.query.table;
    // var columns = req.body.columns;
    var data = dataLoader.getData(table, task_id);

    var cols = data['columnMetas'];
    var results = data['results'];

    var ret = [];
    for(var i=0;i<results.length;i++){
        var item = {};
        for(var j = 0;j<cols.length;j++){
            item[cols[j]['name']]=results[i][j];
        }
        ret.push(item);
    }

    res.json(ret);

});

router.get('/list/:task_id', function (req, res) {
    var task_id = req.params.task_id;
    var tables_s = dataLoader.getTables();
    var tables = [];
    console.log(tables_s.length);

    for(var i=0;i<tables_s.length;i++){
        if(/^\d.*/.test(tables_s[i])){
            continue;
        }
        if(/^kylin.*/.test(tables_s[i]))
            continue;
        tables.push(tables_s[i]);
    }
    var lst = [];
    tables.map(function (table) {
        lst.push({
            name: table,
            url: '/kylin/query?task_id='+task_id+'&table='+table
        });
    });
    res.json(lst);
});

router.get('/table/list/:jid', function (req, res) {
    var jid = req.params.jid;
    PortalJobMeta.findOne({where: {jid: jid}})
        .then(function (item) {
            req.session.master = item.master;
            req.session.port = item.port;
            var ret = request('GET', 'http://'+item.master+':'+item.port+'/resultlist');
            // console.log('Tables: ', ret.getBody('utf8'));
            var result = ret.getBody('utf8');
            var tables = result.split('/');
            tables = tables.slice(0, tables.length-1);
            var lst = [];
            tables.map(function (table) {
                lst.push({
                    name: table,
                    url: '/kylin/table/detail/'+jid+'?table='+table
                });
            });
            res.json(lst);

        });

});

router.get('/table/detail/:jid', function (req, res) {

    var table = req.query.table;
    var jid = req.params.jid;


    PortalJobMeta.findOne({where: {jid: jid}})
        .then(function (item) {

            var master = item.master;
            // var master = '10.141.212.118';
            var port = item.port;
            // var port = '8082';
            if(!master){
                res.status(404).send();
                return;
            }
            console.log("POST", 'http://'+master+':'+port+'/table');
            var ret = request('POST', 'http://'+master+':'+port+'/table', {
                body: table
            });
            var data = JSON.parse(ret.getBody('utf8'));

            // var count = data['count'][0][0];
            var count = data['count'];
            if(count>20000){
                res.json([]);
                return;
            }

            var cols = data['columns'];
            var results = data['data'];

            ret = [];
            for(var i=0;i<results.length;i++){
                var item = {};
                for(var j = 0;j<cols.length;j++){
                    item[cols[j]]=results[i][j];
                }
                ret.push(item);
            }

            res.json(ret);
            // res.json([]);

        });

});

module.exports = router;